'use strict';

const Controller = require('egg').Controller;

class BankController extends Controller {
    async list() {
        const { ctx, app } = this
        const title = ctx.query.title
        ctx.validate({
            title: {
                type: 'string',
                required: false,
                desc: '标题'
            }
        })
        let list, Op = app.Sequelize.Op, where;
        if (title != '' && title != undefined) {
            where = {
                title: {
                    [Op.like]: '%' + title + '%'
                }
            }
        }
        list = await ctx.page(app.model.BankConfig, where)
        ctx.apiSuccess(list)
    }
    //编辑 新增
    async edit() {
        const { ctx, app } = this
        ctx.validate({
            id: {
                type: 'int',
                required: false,
                desc: 'id'
            },
            title: {
                type: 'string',
                required: true,
                desc: '标题'
            },
            logo: {
                type: 'string',
                required: true,
                desc: 'logo'
            },
            bg_image: {
                type: 'string',
                required: true,
                desc: '背景图片'
            }
        })
        const { id, title, logo, bg_image } = ctx.request.body

        let list
        if (id == 0) { //新增
            let listone = await app.model.BankConfig.findOne({ where: { title } })
            if (listone) {
                ctx.throw(400, '标题已存在')
            }
            list = await app.model.BankConfig.create({ title, logo, bg_image })
        } else { //编辑
            let listtwo = await app.model.BankConfig.findByPk(id)
            if (!listtwo) {
                ctx.throw(400, '数据不存在')
            }
            list = await listtwo.update({ title, logo, bg_image })
        }
        ctx.apiSuccess(list)
    }
    //删除
    async del(){
        const {ctx,app}=this
        ctx.validate({
            id:{
                type:'int',
                required:true,
                desc:'id'
            }
        })
        const id=ctx.params.id
        let list=await app.model.BankConfig.destroy({
            where:{
                id
            }
        })
        if(!list){
            ctx.throw(400,'删除失败！')
        }
        ctx.apiSuccess('删除成功')
    }
}

module.exports = BankController;
